<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbItem extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_item';

    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取模板信息
     * @param int  $item_id 模块ID
     * @author MSQ 2021-8-2
    **/
    public function getDetails($item_id = 0,$field = '*')
    {
        $where = [
            'status' => 1,
        ];
        if (is_array($item_id)) {
            $where['id'] = ['IN',$item_id];
            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->column($field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->select();
            }
        }else{
            $where['id'] = $item_id;
            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->value($field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->find();
            }
        }
        
        
        return $info;
    }
    /**
     * 生成随机item_key
     * @param int  $item_key      指定key
     *             $type item类型 1目录2模块
     *             $parent_id     父级item
     * @author MSQ 2021-8-2
    **/
     public function getItemKey($item_key = '',$type = 1,$parent_id = 0)
    {
        if (!$item_key) $item_key = uniqid().'_'.$type.'_'.$parent_id;

        # 验证唯一性
        $isExist = $this->where(['item_key' => $item_key])->value('id');
        if ($isExist) $this->getItemKey('',$type,$parent_id);
        return $item_key;
    }
    /**
     * 获取目录/模块信息
     * @param int  $item_key
     * @author MSQ 2021-8-5
    **/
    public function getInfoByItemKey($item_key = '',$field = '*')
    {
        $where = [
            'item_key' => $item_key,
            'status'   => 1
        ];
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where($where)->value($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->find();
        }
        return $info;
    }
    /**
     * 获取基础模块信息
     * @author MSQ 2021-8-5
     */
    function getBasicItemInfo($field = '*')
    {
        $basicItemKey = $this->getBasicItemKey();
        $info = $this->getInfoByItemKey($basicItemKey,$field);
        
        return $info;
    }
    /**
     * 获取基础模块key
     * @author MSQ 2021-8-19
     */
    public function getBasicItemKey()
    {
        $key = 'user_info_new';
        // $key = 'user_info';
        return $key;
    }
    /**
     * 获取基础信息目录key
     * @author MSQ 2021-9-1
     */
    public function getBasicDirKey()
    {
        $key = 'basic_info_new';
        // $key = 'basic_info';
        return $key;
    }
    /**
     * 获取QID变量的key
     * @author MSQ 2021-10-18
     */
    public function getUserNumberKey()
    {
        $basicItemKey = $this->getBasicItemKey();
        $userNumberKey = 'user_number';

        $key = $basicItemKey.'__'.$userNumberKey;

        return $key;
    }
    
    /**
     * 获取基础信息相关item
     * 作用于引用模板时同步新增目录&模块过滤掉基础信息
     * @author MSQ 2021-9-1
     */
    public function getBasicDirChildItem()
    {
        # 基础信息key
        $key = $this->getBasicDirKey();
        if (!$key) return true;

        $itemInfo = $this->getInfoByItemKey($key);
        if (!$itemInfo) return false;
        # 将自身放进去
        $data[] = $itemInfo;
        # 递归获取其下目录&模块
        $info = $this->recursionGetChildItemByKey($itemInfo['id'],$data);
        return $info;
    }
    /**
     * 根据item_id递归获取所有下级
     * @author MSQ 2021-9-1
     */
    public function recursionGetChildItemByKey($item_id = 0,$data = [])
    {
        if (!is_array($item_id)) $item_id = [$item_id];
        # 子目录&模块信息
        $childList = $this->customQuery(['parent_id' => ['IN',$item_id]]);
        if (!$childList) return $data;

        $data = array_merge($data,$childList);

        $item_id = array_column($childList,'id');
        return $this->recursionGetChildItemByKey($item_id,$data);
    }
    /**
     * 自定义SQL
     * @author MSQ 2021-9-1
     */
    public function customQuery($where = [],$field = '')
    {
        $where['status'] = 1;

        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where($where)->column($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->select();
        }

        return $info;
    }
    /**
     * 获取下级目录/模块
     * @author MSQ 2021-10-15
     */
    public function getChildItem($item_id = [],$field = '*')
    {
        if (!$item_id) return [];
        if (!is_array($item_id)) $item_id = [$item_id];
        
        $where = [
            'parent_id'   => ['IN',$item_id],
            'status'      => 1,
        ];
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = db($this->dbName)->where($where)->column($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->select();
        }

        return $info;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------
    # -------------------------------- 验证类接口 START -----------------------------------

    # --------------------------------- 验证类接口 END ------------------------------------
    
    # ------------------------------- 数据处理类接口 START----------------------------------
    public function createItem($data = []){

        if (!$data['template_id'] || !$data['item_name'] || !$data['type']) return false;

        if (!in_array($data['type'],[1,2])) return false;

        $addData = [
            'template_id' => $data['template_id'],
            'item_name'   => $data['item_name'],
            'parent_id'   => $data['parent_id'],
            'type'        => $data['type'],
            // 'classify_rank'  => $classify_rank,
            // 'item_key'       => $this->getItemKey('',$type,$parent_id),
            'usercare_id' => $data['usercare_id'],
        ];
        if (!isset($data['classify_rank']) || !$data['classify_rank']) {
            $parInfoType = $this->getDetails($parent_id,'type');
            $addData['classify_rank'] = $parInfoType==$data['type'] ? 2 : 1;
        }
        $addData['item_key'] = isset($addData['item_key']) && $addData['item_key'] ? $addData['item_key'].'&'.uniqid() : $this->getItemKey('',$data['type'],$data['parent_id']);

        $this->setAttr('id',null)->isUpdate(false)->save($addData);
        if (!isset($this->id)) return false;
        return $this->id;
    }
    /**
     * 根据删除目录/模块
     * @param [type] $item_id 模块id
     * @author MSQ   2021-8-21
     */
    public function deleteItemByIds($item_id = [])
    {
        if (!$item_id) return false;

        if (!is_array($item_id)) $item_id = [$item_id];

        $where = [
            'status' => 1,
            'id'     => ['IN',$item_id]
        ];
        $res = $this->update(['status' => 0],$where);
        if (!$res) return false;
        return true;
    }
    /**
     * 添加数据
     * @param [type] $item_id 模块id
     * @author MSQ   2021-8-21
     */
    public function addData($data = [])
    {
        if (!$data) return false;
        
        $this->setAttr('id',null)->isUpdate(false)->save($data);
        if (!isset($this->id)) return false;

        return $this->id;
    }
    # -------------------------------- 数据处理类接口 END----------------------------------

}
